<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传文件"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="upload-container">
      <!-- 拖拽上传区域 -->
      <div
        class="upload-dragger"
        :class="{ 'is-dragover': isDragOver }"
        @drop="handleDrop"
        @dragover="handleDragOver"
        @dragleave="handleDragLeave"
        @click="handleClick"
      >
        <el-icon class="upload-icon">
          <Upload />
        </el-icon>
        <div class="upload-text">
          <p>点击或拖拽文件到此区域上传</p>
          <p class="upload-tip">支持单个或批量上传</p>
        </div>
      </div>

      <!-- 文件列表 -->
      <div v-if="fileList.length > 0" class="file-list">
        <div class="file-list-header">
          <span>文件列表 ({{ fileList.length }})</span>
          <el-button type="text" @click="clearFiles">清空</el-button>
        </div>
        
        <div class="file-items">
          <div
            v-for="(file, index) in fileList"
            :key="index"
            class="file-item"
            :class="{ 'is-error': file.status === 'error' }"
          >
            <div class="file-info">
              <el-icon class="file-icon">
                <Document />
              </el-icon>
              <div class="file-details">
                <div class="file-name">{{ file.name }}</div>
                <div class="file-size">{{ formatFileSize(file.size) }}</div>
              </div>
            </div>
            
            <div class="file-progress">
              <el-progress
                :percentage="file.progress"
                :status="file.status === 'error' ? 'exception' : file.status === 'success' ? 'success' : undefined"
                :show-text="false"
              />
            </div>
            
            <div class="file-actions">
              <el-button
                v-if="file.status === 'uploading'"
                type="text"
                size="small"
                @click="pauseUpload(index)"
              >
                暂停
              </el-button>
              <el-button
                v-if="file.status === 'paused'"
                type="text"
                size="small"
                @click="resumeUpload(index)"
              >
                继续
              </el-button>
              <el-button
                v-if="file.status === 'error'"
                type="text"
                size="small"
                @click="retryUpload(index)"
              >
                重试
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="removeFile(index)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 上传设置 -->
      <div class="upload-settings">
        <el-form :model="settings" label-width="100px">
          <el-form-item label="文件命名">
            <el-radio-group v-model="settings.namingRule">
              <el-radio label="original">保持原名</el-radio>
              <el-radio label="timestamp">时间戳</el-radio>
              <el-radio label="uuid">UUID</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="重复处理">
            <el-radio-group v-model="settings.duplicateRule">
              <el-radio label="skip">跳过</el-radio>
              <el-radio label="overwrite">覆盖</el-radio>
              <el-radio label="rename">重命名</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleUpload"
          :disabled="fileList.length === 0 || isUploading"
          :loading="isUploading"
        >
          {{ isUploading ? '上传中...' : '开始上传' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Document } from '@element-plus/icons-vue'
import { fileApi } from '@/api/cd'

interface Props {
  visible: boolean
  folderId: number | string
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'upload-success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 拖拽状态
const isDragOver = ref(false)

// 文件列表
interface FileItem {
  file: File
  name: string
  size: number
  progress: number
  status: 'pending' | 'uploading' | 'paused' | 'success' | 'error'
  error?: string
}

const fileList = ref<FileItem[]>([])
const isUploading = ref(false)

// 上传设置
const settings = reactive({
  namingRule: 'original',
  duplicateRule: 'rename'
})

// 文件输入框
let fileInput: HTMLInputElement | null = null

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    createFileInput()
  } else {
    clearFiles()
  }
})

// 创建文件输入框
const createFileInput = () => {
  if (fileInput) {
    fileInput.remove()
  }
  
  fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.multiple = true
  fileInput.style.display = 'none'
  fileInput.addEventListener('change', handleFileSelect)
  document.body.appendChild(fileInput)
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = Array.from(target.files || [])
  addFiles(files)
  
  // 清空input值，允许重复选择相同文件
  target.value = ''
}

// 添加文件
const addFiles = (files: File[]) => {
  files.forEach(file => {
    // 检查文件大小限制，从配置文件读取（默认200MB）
    const maxFileSize = import.meta.env.VITE_APP_MAX_FILE_SIZE || 200 * 1024 * 1024
    const maxFileSizeMB = maxFileSize / (1024 * 1024)
    if (file.size > maxFileSize) {
      ElMessage.error(`文件 "${file.name}" 超过${maxFileSizeMB}MB限制`)
      return
    }
    
    // 检查是否已存在
    const exists = fileList.value.some(item => 
      item.name === file.name && item.size === file.size
    )
    
    if (exists) {
      ElMessage.warning(`文件 "${file.name}" 已存在`)
      return
    }
    
    fileList.value.push({
      file,
      name: file.name,
      size: file.size,
      progress: 0,
      status: 'pending'
    })
  })
}

// 拖拽处理
const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
  
  const files = Array.from(event.dataTransfer?.files || [])
  addFiles(files)
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = () => {
  isDragOver.value = false
}

const handleClick = () => {
  fileInput?.click()
}

// 文件操作
const removeFile = (index: number) => {
  fileList.value.splice(index, 1)
}

const clearFiles = () => {
  fileList.value = []
}

const pauseUpload = (index: number) => {
  // TODO: 实现暂停上传
  fileList.value[index].status = 'paused'
}

const resumeUpload = (index: number) => {
  // TODO: 实现继续上传
  fileList.value[index].status = 'uploading'
}

const retryUpload = (index: number) => {
  // TODO: 实现重试上传
  fileList.value[index].status = 'pending'
  fileList.value[index].progress = 0
  fileList.value[index].error = undefined
}

// 上传文件
const handleUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  // 检查文件夹ID
  if (!props.folderId) {
    ElMessage.error('请先选中要上传文件的文件夹')
    return
  }
  
  isUploading.value = true
  
  try {
    const uploadPromises = fileList.value
      .filter(item => item.status === 'pending' || item.status === 'error')
      .map(async (item, index) => {
        try {
          item.status = 'uploading'
          item.progress = 0
          
          // 模拟上传进度
          const progressInterval = setInterval(() => {
            if (item.status === 'uploading' && item.progress < 90) {
              item.progress += Math.random() * 10
            }
          }, 200)
          
          const response = await fileApi.upload(item.file, props.folderId)
          
          clearInterval(progressInterval)
          item.progress = 100
          item.status = 'success'
          
          return response
        } catch (error) {
          item.status = 'error'
          item.error = error instanceof Error ? error.message : '上传失败'
          throw error
        }
      })
    
    await Promise.all(uploadPromises)
    
    ElMessage.success('文件上传成功')
    emit('upload-success')
    handleClose()
    
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('部分文件上传失败')
  } finally {
    isUploading.value = false
  }
}

// 格式化文件大小
const formatFileSize = (size: number): string => {
  if (size < 1024) {
    return `${size} B`
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(1)} KB`
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / (1024 * 1024)).toFixed(1)} MB`
  } else {
    return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`
  }
}

// 关闭对话框
const handleClose = () => {
  if (fileInput) {
    fileInput.remove()
    fileInput = null
  }
  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.upload-container {
  .upload-dragger {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    width: 100%;
    height: 180px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: border-color 0.3s;
    
    &:hover,
    &.is-dragover {
      border-color: #409eff;
    }
    
    .upload-icon {
      font-size: 48px;
      color: #c0c4cc;
      margin-bottom: 16px;
    }
    
    .upload-text {
      color: #606266;
      
      p {
        margin: 0 0 8px 0;
        font-size: 16px;
      }
      
      .upload-tip {
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .file-list {
    margin-top: 24px;
    
    .file-list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      font-weight: 500;
    }
    
    .file-items {
      max-height: 300px;
      overflow-y: auto;
      
      .file-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 8px;
        
        &.is-error {
          border-color: #f56c6c;
          background-color: #fef0f0;
        }
        
        .file-info {
          display: flex;
          align-items: center;
          flex: 1;
          min-width: 0;
          
          .file-icon {
            margin-right: 12px;
            color: #409eff;
          }
          
          .file-details {
            flex: 1;
            min-width: 0;
            
            .file-name {
              font-size: 14px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .file-size {
              font-size: 12px;
              color: #909399;
              margin-top: 4px;
            }
          }
        }
        
        .file-progress {
          width: 120px;
          margin: 0 16px;
        }
        
        .file-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }
  
  .upload-settings {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #e4e7ed;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
